package algorithm.recursion.tree;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜单树
 *
 * @author hupan
 * @date 2021-07-14 20:55
 */
public class MenuTree {
    private List<Menu> menuList = new ArrayList<>();

    public MenuTree(List<Menu> menuList) {
        this.menuList = menuList;
    }

    //建立树形结构
    public List<Menu> builTree() {
        List<Menu> treeMenus = new ArrayList<>();
        for (Menu menuNode : getRootNode()) {
            menuNode = buildChilTree(menuNode);
            treeMenus.add(menuNode);
        }

        return treeMenus;
    }

    //递归，建立子树形结构
    private Menu buildChilTree(Menu pNode) {
        List<Menu> chilMenus = new ArrayList<>();
        for (Menu menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(buildChilTree(menuNode));
            }
        }

        return pNode.setChildren(chilMenus);
    }

    //获取根节点
    private List<Menu> getRootNode() {
        List<Menu> rootMenuLists = new ArrayList<>();
        for (Menu menuNode : menuList) {
            if ("0".equals(menuNode.getParentId())) {
                rootMenuLists.add(menuNode);
            }
        }

        return rootMenuLists;
    }

    public static void main(String[] args) throws IOException {
        List<Menu> menuList = new ArrayList<>();
        /*插入一些数据*/
        menuList.add(new Menu("GN001D000", "0", "系统管理", "/admin", "Y"));
        menuList.add(new Menu("GN001D100", "GN001D000", "权限管理", "/admin", "Y"));
        menuList.add(new Menu("GN001D110", "GN001D100", "密码修改", "/admin", "Y"));
        menuList.add(new Menu("GN001D120", "GN001D100", "新加用户", "/admin", "Y"));
        menuList.add(new Menu("GN001D200", "GN001D000", "系统监控", "/admin", "Y"));
        menuList.add(new Menu("GN001D210", "GN001D200", "在线用户", "/admin", "Y"));
        menuList.add(new Menu("GN002D000", "0", "订阅区", "/admin", "Y"));
        menuList.add(new Menu("GN003D000", "0", "未知领域", "/admin", "Y"));

        /*让我们构建树*/
        MenuTree menuTree = new MenuTree(menuList);
        menuList = menuTree.builTree();

        /*转为json看看效果*/
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonOutput = objectMapper.writeValueAsString(menuList);

        System.out.println(jsonOutput);
    }

}